<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function treeToArray(tree) {
        return tree.reduce((res, item) => {
          const { children, ...rest } = item;

          return res.concat(
            rest,
            children && children.length ? treeToArray(children) : []
          );
        }, []);
      }

      function spliceTree(tree, targetId) {
        for (let item of tree) {
          console.log(item, targetId);
          if (item.id === targetId) {
            console.log("yes", item);
            return item;
          }
          if (item.children && item.children.length) {
            return spliceTree(item.children, targetId);
          }
        }

        return [];
      }

      fetch(
        "https://mock.presstime.cn/mock/65a8725d9358b0b690cebae9/tree"
      ).then((res) => {
        res.json().then((res) => {
          console.log("res:", res);

          const targetId = 2002781;

          console.log("spliceTree:", spliceTree(res.data, targetId));

          //   var parentId = [];

          //   function addParentIdToEmployees(node, parentIds = []) {
          //     node.employees.forEach((employee) => {
          //       employee.parentId = [...parentIds, node.id];
          //     });

          //     if (node.children) {
          //       node.children.forEach((child) => {
          //         addParentIdToEmployees(child, [...parentIds, node.id]);
          //         parentId.push(node.id);
          //       });
          //     }
          //   }

          //   res.data.forEach((item) => {
          //     addParentIdToEmployees(item);
          //   });

          //   console.log("所有parentId:", new Set(parentId));

          //   const result = treeToArray(res.data);
          //   console.log("result:", result);
        });
      });
    </script>
  </body>
</html>
